package cn.hhchat.wp.service;

import cn.hhchat.wp.entity.RoleEntity;
import cn.hhchat.wp.entity.UserEntity;
import cn.hhchat.wp.enums.RoleEnum;
import cn.hhchat.wp.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created this one by HMH on 2017/10/22.
 */
@Service
@Transactional
public class RoleService {

    public UserEntity setRole(UserEntity userEntity, RoleEnum roleEnum) {
        if(userEntity.getRoles().stream().filter(r -> r.getName().equals(roleEnum.name())).count() > 0){
            return userEntity;
        }
        userEntity.getRoles().add(getByName(roleEnum));
        return userEntity;
    }

    public List<UserEntity> getAllAdmin() {
        RoleEntity role = getByName(RoleEnum.管理员);
        return userService.getAllUserInRole(role);
    }

    public void setAdminInBatch(List<UserEntity> users){
        List<UserEntity> adminUsers = this.getAllAdmin();
        adminUsers.forEach(u->this.removeRole(u,RoleEnum.管理员));
        users.forEach(u -> this.setRole(u, RoleEnum.管理员));
    }

    public RoleEntity save(RoleEntity role) {
        return roleRepository.save(role);
    }

    public UserEntity removeRole(UserEntity userEntity, RoleEnum roleEnum) {
        for (RoleEntity roleEntity : userEntity.getRoles()) {
            if (roleEntity.getName().equals(roleEnum.name())) {
                userEntity.getRoles().remove(roleEntity);
                break;
            }
        }
        return userService.save(userEntity);
    }

    public RoleEntity getByName(String name) {
        return roleRepository.findByName(name);
    }

    public RoleEntity getByName(RoleEnum roleEnum) {
        return roleRepository.findByName(roleEnum.name());
    }

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private UserService userService;

}
